<template>
  <XenFormPopup
    ref="popupRef"
    :title="config.title"
    :subtitle="config.subtitle"
    :confirm-text="config.confirmText"
    :loading-text="config.loadingText"
    :loading="loading"
    @confirm="handleConfirm"
    @close="handleClose"
  >
    <template #form>
      <uni-forms ref="formRef" :model="formData" :rules="formRules">
        <!-- 动态渲染表单区块 -->
        <view
          v-for="section in config.sections"
          :key="section.key"
          class="form-section"
        >
          <view class="section-header">
            <view class="section-icon">
              <uni-icons
                :type="section.icon"
                size="20"
                color="#ffffff"
              ></uni-icons>
            </view>
            <view class="section-title">
              <text class="title">{{ section.title }}</text>
              <text class="subtitle">{{ section.subtitle }}</text>
            </view>
          </view>

          <view class="section-content">
            <!-- 部门输入方式选择（仅在包含部门字段的区块显示） -->
            <view
              v-if="hasDepartmentFields(section)"
              class="department-input-method-section"
            >
              <view class="method-label">部门输入方式：</view>
              <uni-data-checkbox
                v-model="departmentInputMethod[getDepartmentMethodKey(section)]"
                :localdata="departmentInputOptions"
                mode="button"
                @change="
                  (e: any) =>
                    handleDepartmentMethodChange(
                      getDepartmentMethodKey(section),
                      e,
                    )
                "
              />
            </view>

            <!-- 手动输入模式下的合并字段 -->
            <view
              v-if="
                hasDepartmentFields(section) &&
                getCurrentSectionInputMethod(section) === 'manual'
              "
              class="input-row single"
            >
              <view class="input-group">
                <view class="input-label">
                  <uni-icons type="home" size="18" color="#14b8a6"></uni-icons>
                  <text class="label-text">
                    {{ getCombinedFieldLabel(section) }}
                  </text>
                </view>
                <uni-forms-item :name="getCombinedFieldKey(section)">
                  <uni-easyinput
                    v-model="formData[getCombinedFieldKey(section)]"
                    :placeholder="getCombinedFieldPlaceholder(section)"
                    :clearable="false"
                    class="custom-input"
                  />
                </uni-forms-item>
              </view>
            </view>

            <!-- 动态渲染字段行 -->
            <view
              v-for="row in section.rows"
              :key="row.key"
              class="input-row"
              :class="{ single: row.fields.length === 1 }"
            >
              <!-- 动态渲染字段 -->
              <view
                v-for="field in row.fields"
                :key="field.key"
                class="input-group"
                v-show="shouldShowField(field, section)"
              >
                <view class="input-label">
                  <uni-icons
                    :type="field.icon"
                    size="18"
                    color="#14b8a6"
                  ></uni-icons>
                  <text class="label-text">
                    {{ field.label }}
                    <text v-if="field.required" class="required">*</text>
                  </text>
                </view>

                <!-- 文本输入框 -->
                <uni-forms-item v-if="field.type === 'input'" :name="field.key">
                  <uni-easyinput
                    v-model="formData[field.key]"
                    :placeholder="field.placeholder"
                    :type="field.inputType || 'text'"
                    :maxlength="field.maxlength"
                    :clearable="false"
                    class="custom-input"
                  />
                </uni-forms-item>

                <!-- 文本域 -->
                <uni-forms-item
                  v-else-if="field.type === 'textarea'"
                  :name="field.key"
                >
                  <uni-easyinput
                    v-model="formData[field.key]"
                    :placeholder="field.placeholder"
                    type="textarea"
                    :autoHeight="true"
                    :maxlength="field.maxlength || 500"
                    :clearable="false"
                    class="custom-textarea"
                  />
                </uni-forms-item>

                <!-- 标准部门选择器 -->
                <uni-forms-item
                  v-if="field.type === 'picker' && isDepartmentField(field.key)"
                  :name="field.key"
                >
                  <!-- 选择输入框模式 -->
                  <XenDepartmentPicker
                    v-if="
                      getCurrentDepartmentInputMethod(field.key) === 'select'
                    "
                    v-model="formData[field.key]"
                    :placeholder="field.placeholder"
                    :department-data="departmentData"
                    @change="handleDepartmentChange"
                  />

                  <!-- 手动输入模式 -->
                  <uni-easyinput
                    v-else-if="
                      getCurrentDepartmentInputMethod(field.key) === 'manual'
                    "
                    v-model="formData[field.key + '_manual']"
                    :placeholder="'请手动输入' + field.label"
                    :clearable="false"
                    class="custom-input"
                  />
                </uni-forms-item>

                <!-- 普通Picker选择器 - APP端使用专用组件 -->
                <!-- #ifdef APP-PLUS -->
                <uni-forms-item
                  v-else-if="field.type === 'picker'"
                  :name="field.key"
                >
                  <XenAppSelector
                    :model-value="formData[field.key]"
                    :options="getPickerRange(field)"
                    :placeholder="
                      isPickerDisabled(field)
                        ? getDisabledPlaceholder(field)
                        : field.placeholder
                    "
                    :disabled="isPickerDisabled(field)"
                    :option-text-field="field.rangeKey || 'text'"
                    :option-value-field="'value'"
                    @update:model-value="
                      (value) => handleAppSelectorChange(field.key, field, value)
                    "
                  />
                </uni-forms-item>
                <!-- #endif -->

                <!-- 普通Picker选择器 - 其他平台使用原生picker -->
                <!-- #ifndef APP-PLUS -->
                <uni-forms-item
                  v-else-if="field.type === 'picker'"
                  :name="field.key"
                >
                  <picker
                    class="custom-picker"
                    mode="selector"
                    :range="getPickerRange(field)"
                    :range-key="field.rangeKey || 'text'"
                    :value="getPickerIndex(field.key, field)"
                    :disabled="isPickerDisabled(field)"
                    @change="
                      (e: any) => handlePickerChange(field.key, field, e)
                    "
                  >
                    <view
                      class="picker-content"
                      :class="{ disabled: isPickerDisabled(field) }"
                    >
                      <text
                        class="picker-text"
                        :class="{
                          'has-value': getPickerDisplayText(field.key, field),
                          disabled: isPickerDisabled(field),
                        }"
                        >{{
                          isPickerDisabled(field)
                            ? getDisabledPlaceholder(field)
                            : getPickerDisplayText(field.key, field) ||
                              field.placeholder
                        }}</text
                      >
                      <uni-icons
                        type="down"
                        size="16"
                        :color="isPickerDisabled(field) ? '#ccc' : '#999'"
                      ></uni-icons>
                    </view>
                  </picker>
                </uni-forms-item>
                <!-- #endif -->

                <!-- 日期选择器 - APP端使用专用组件 -->
                <!-- #ifdef APP-PLUS -->
                <uni-forms-item
                  v-else-if="field.type === 'date'"
                  :name="field.key"
                >
                  <XenAppDatePicker
                    :model-value="formData[field.key]"
                    :placeholder="field.placeholder"
                    @update:model-value="
                      (value) => handleAppDateChange(field.key, value)
                    "
                  />
                </uni-forms-item>
                <!-- #endif -->

                <!-- 日期选择器 - 其他平台使用原生picker -->
                <!-- #ifndef APP-PLUS -->
                <uni-forms-item
                  v-else-if="field.type === 'date'"
                  :name="field.key"
                >
                  <picker
                    class="custom-picker"
                    mode="date"
                    :value="formData[field.key]"
                    @change="(e: any) => handleDateChange(field.key, e)"
                  >
                    <view class="picker-content">
                      <text
                        class="picker-text"
                        :class="{ 'has-value': formData[field.key] }"
                        >{{ formData[field.key] || field.placeholder }}</text
                      >
                      <uni-icons type="down" size="16" color="#999"></uni-icons>
                    </view>
                  </picker>
                </uni-forms-item>
                <!-- #endif -->

                <!-- 日期时间选择器 -->
                <uni-forms-item
                  v-else-if="field.type === 'datetime'"
                  :name="field.key"
                >
                  <uni-datetime-picker
                    v-model="formData[field.key]"
                    type="date"
                    :placeholder="field.placeholder"
                    class="custom-picker"
                  />
                </uni-forms-item>

                <!-- 文件上传 -->
                <view
                  v-else-if="field.type === 'file'"
                  class="file-upload-container"
                >
                  <uni-file-picker
                    v-model="fileValues[field.key]"
                    fileMediatype="all"
                    mode="list"
                    limit="1"
                    :title="field.placeholder"
                    :delIcon="true"
                    @select="(e) => selectFile(field.key, e)"
                    @success="(e) => uploadFileSuccess(field.key, e)"
                    @fail="(e) => uploadFileFail(field.key, e)"
                    @delete="(e) => deleteFile(field.key, e)"
                  ></uni-file-picker>

                  <!-- 文件预览按钮 -->
                  <view
                    v-if="formData[field.key]"
                    class="file-preview-btn"
                    @tap="() => previewFile(field.key)"
                  >
                    <view class="preview-content">
                      <uni-icons
                        type="eye"
                        size="16"
                        color="#14b8a6"
                      ></uni-icons>
                      <text class="preview-text">预览文件</text>
                    </view>
                  </view>

                  <view class="upload-tips">
                    <text>{{ field.tips || "支持Word、PDF、图片格式" }}</text>
                  </view>
                </view>

                <!-- 多文件上传 -->
                <view
                  v-else-if="field.type === 'multifile'"
                  class="file-upload-container"
                >
                  <uni-file-picker
                    v-model="fileValues[field.key]"
                    fileMediatype="all"
                    mode="list"
                    limit="9"
                    :title="field.placeholder"
                    :delIcon="true"
                    @select="(e) => selectMultiFile(field.key, e)"
                    @success="(e) => uploadMultiFileSuccess(field.key, e)"
                    @fail="(e) => uploadMultiFileFail(field.key, e)"
                    @delete="(e) => deleteMultiFile(field.key, e)"
                  ></uni-file-picker>

                  <!-- 多文件预览按钮 -->
                  <view
                    v-if="
                      formData[field.key] && getFileIds(field.key).length > 0
                    "
                    class="multi-file-preview"
                  >
                    <view
                      v-for="(fileId, index) in getFileIds(field.key)"
                      :key="fileId"
                      class="file-preview-btn"
                      @tap="() => previewMultiFile(field.key, index)"
                    >
                      <view class="preview-content">
                        <uni-icons
                          type="eye"
                          size="16"
                          color="#14b8a6"
                        ></uni-icons>
                        <text class="preview-text"
                          >预览文件{{ index + 1 }}</text
                        >
                      </view>
                    </view>
                  </view>

                  <view class="upload-tips">
                    <text>{{
                      field.tips || "支持Word、PDF、图片格式，可上传多个文件"
                    }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </uni-forms>
    </template>
  </XenFormPopup>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import XenFormPopup from "@/components/XenFormPopup.vue";
import XenDepartmentPicker from "@/components/XenDepartmentPicker.vue";
import XenAppSelector from "@/components/XenAppSelector.vue";
import XenAppDatePicker from "@/components/XenAppDatePicker.vue";
import { uploadImage } from "../../../../utils/unirequest";
import useActivityApi from "../../api/index";

const api = useActivityApi();

// 定义配置接口
interface FieldConfig {
  key: string;
  label: string;
  type:
    | "input"
    | "textarea"
    | "picker"
    | "date"
    | "datetime"
    | "file"
    | "multifile";
  icon: string;
  placeholder: string;
  required?: boolean;
  inputType?: string;
  maxlength?: number;
  pattern?: string; // 正则表达式验证
  patternErrorMessage?: string; // 正则验证失败的错误信息
  options?: { value: any; text: string }[];
  rangeKey?: string; // picker模式下用于指定显示的字段名
  tips?: string;
  defaultValue?: any; // 默认值
}

interface RowConfig {
  key: string;
  fields: FieldConfig[];
}

interface SectionConfig {
  key: string;
  title: string;
  subtitle: string;
  icon: string;
  rows: RowConfig[];
}

interface PopupConfig {
  title: string;
  subtitle: string;
  confirmText: string;
  loadingText: string;
  sections: SectionConfig[];
}

// Props
interface Props {
  show: boolean;
  config: PopupConfig;
  personId?: string;
  editData?: any;
  onSubmit?: (data: any) => Promise<void>;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  "update:show": [value: boolean];
  confirm: [];
}>();

// 弹窗引用
const popupRef = ref();
const formRef = ref();

// 状态管理
const loading = ref(false);
const formData = ref<Record<string, any>>({});
const fileValues = ref<Record<string, any[]>>({});

// 部门和岗位数据
const departmentData = ref<any[]>([]);
const originalPositionOptions = ref<any[]>([]);
const newPositionOptions = ref<any[]>([]);

// 部门输入方式状态
const departmentInputMethod = ref<Record<string, string>>({});
const departmentInputOptions = ref([
  { value: "select", text: "选择输入框" },
  { value: "manual", text: "手动输入" },
]);

// 表单验证规则
const formRules = computed(() => {
  const rules: Record<string, any> = {};

  props.config.sections.forEach((section) => {
    section.rows.forEach((row) => {
      row.fields.forEach((field) => {
        const fieldRules: any[] = [];

        // 必填验证
        if (field.required) {
          fieldRules.push({
            required: true,
            errorMessage: `请${field.type === "picker" ? "选择" : "输入"}${
              field.label
            }`,
          });
        }

        // 正则验证
        if (field.pattern) {
          fieldRules.push({
            pattern: field.pattern,
            errorMessage:
              field.patternErrorMessage || `${field.label}格式不正确`,
          });
        }

        if (fieldRules.length > 0) {
          rules[field.key] = {
            rules: fieldRules,
          };
        }
      });
    });

    // 为合并字段添加验证规则（非必填）
    if (hasDepartmentFields(section)) {
      const combinedKey = getCombinedFieldKey(section);
      rules[combinedKey] = {
        rules: [
          // 合并字段不是必填的，所以不添加required验证
        ],
      };
    }
  });

  return rules;
});

// 初始化表单数据
const initFormData = (preserveExisting = false) => {
  // 清空动态选项（仅在不保留现有数据时）
  if (!preserveExisting) {
    dynamicOptions.value = {};
  }

  const data: Record<string, any> = preserveExisting
    ? { ...formData.value }
    : {};
  const files: Record<string, any[]> = preserveExisting
    ? { ...fileValues.value }
    : {};

  props.config.sections.forEach((section) => {
    section.rows.forEach((row) => {
      row.fields.forEach((field) => {
        // 如果preserveExisting为true且字段已有值，则保留现有值
        if (
          preserveExisting &&
          data.hasOwnProperty(field.key) &&
          data[field.key] !== ""
        ) {
          return; // 保留现有值，不覆盖
        }

        // 如果字段有默认值，使用默认值，否则使用空字符串
        data[field.key] =
          field.defaultValue !== undefined ? field.defaultValue : "";
        if (field.type === "file" || field.type === "multifile") {
          files[field.key] = files[field.key] || [];
        }

        // 初始化部门输入方式，默认为选择输入框
        if (isDepartmentField(field.key)) {
          const methodKey =
            field.key === "OriginalGroupId" ? "original" : "new";
          if (!preserveExisting || !departmentInputMethod.value[methodKey]) {
            departmentInputMethod.value[methodKey] = "select";
          }
        }
      });
    });

    // 初始化合并字段
    if (hasDepartmentFields(section)) {
      const combinedKey = getCombinedFieldKey(section);
      if (!preserveExisting || !data.hasOwnProperty(combinedKey)) {
        data[combinedKey] = "";
      }
    }
  });

  formData.value = data;
  fileValues.value = files;
};

// 判断区块是否包含部门字段
const hasDepartmentFields = (section: any) => {
  return section.rows.some((row: any) =>
    row.fields.some((field: any) => isDepartmentField(field.key)),
  );
};

// 获取区块对应的部门输入方式键
const getDepartmentMethodKey = (section: any) => {
  if (section.key === "original_position") {
    return "original";
  } else if (section.key === "new_position") {
    return "new";
  }
  return section.key;
};

// 获取当前部门字段的输入方式
const getCurrentDepartmentInputMethod = (fieldKey: string) => {
  if (fieldKey === "OriginalGroupId") {
    return departmentInputMethod.value["original"] || "select";
  } else if (fieldKey === "NewGroupId") {
    return departmentInputMethod.value["new"] || "select";
  }
  return "select";
};

// 获取当前区块的输入方式
const getCurrentSectionInputMethod = (section: any) => {
  const methodKey = getDepartmentMethodKey(section);
  return departmentInputMethod.value[methodKey] || "select";
};

// 获取合并字段的标签
const getCombinedFieldLabel = (section: any) => {
  if (section.key === "original_position") {
    return "原部门岗位";
  } else if (section.key === "new_position") {
    return "新部门岗位";
  }
  return "部门岗位";
};

// 获取合并字段的键
const getCombinedFieldKey = (section: any) => {
  if (section.key === "original_position") {
    return "OriginalDepartmentPosition";
  } else if (section.key === "new_position") {
    return "NewDepartmentPosition";
  }
  return "DepartmentPosition";
};

// 获取合并字段的占位符
const getCombinedFieldPlaceholder = (section: any) => {
  if (section.key === "original_position") {
    return '请输入"部门-岗位"';
  } else if (section.key === "new_position") {
    return '请输入"部门-岗位"';
  }
  return '请输入"部门-岗位"';
};

// 判断字段是否应该显示
const shouldShowField = (field: any, section: any) => {
  const currentMethod = getCurrentSectionInputMethod(section);

  // 在手动输入模式下，隐藏部门和岗位字段
  if (currentMethod === "manual") {
    if (isDepartmentField(field.key) || isPositionField(field.key)) {
      return false;
    }
  }

  return true;
};

// 判断是否为岗位字段
const isPositionField = (fieldKey: string) => {
  return fieldKey === "OriginalPositionId" || fieldKey === "NewPositionId";
};

// 处理部门输入方式变化
const handleDepartmentMethodChange = (methodKey: string, e: any) => {
  const newMethod = e.detail.value;
  departmentInputMethod.value[methodKey] = newMethod;

  // 根据方式键确定对应的字段
  let departmentField = "";
  let positionField = "";
  let positionOptions: any = null;
  let combinedField = "";

  if (methodKey === "original") {
    departmentField = "OriginalGroupId";
    positionField = "OriginalPositionId";
    positionOptions = originalPositionOptions;
    combinedField = "OriginalDepartmentPosition";
  } else if (methodKey === "new") {
    departmentField = "NewGroupId";
    positionField = "NewPositionId";
    positionOptions = newPositionOptions;
    combinedField = "NewDepartmentPosition";
  }

  // 清空对应的表单数据
  if (newMethod === "select") {
    // 切换到选择模式时，清空手动输入的数据
    formData.value[departmentField + "_manual"] = "";
    formData.value[combinedField] = "";
  } else if (newMethod === "manual") {
    // 切换到手动输入模式时，清空选择的数据
    formData.value[departmentField] = "";
    formData.value[departmentField + "_manual"] = "";
    // 同时清空对应的岗位选择
    if (positionField) {
      formData.value[positionField] = "";
      if (positionOptions) {
        positionOptions.value = [];
      }
    }
  }
};

// 日期选择处理
const handleDateChange = (fieldKey: string, e: any) => {
  formData.value[fieldKey] = e.detail.value;
};

// APP端日期选择处理
const handleAppDateChange = (fieldKey: string, value: string) => {
  formData.value[fieldKey] = value;
};

// 获取picker的选项数组
const getPickerRange = (field: FieldConfig) => {
  // 对于岗位字段，使用动态加载的选项
  if (field.key === "OriginalPositionId") {
    return originalPositionOptions.value;
  } else if (field.key === "NewPositionId") {
    return newPositionOptions.value;
  }
  return getFieldOptions(field);
};

// 获取picker当前选中的索引
const getPickerIndex = (fieldKey: string, field: FieldConfig) => {
  const currentValue = formData.value[fieldKey];
  if (!currentValue) return 0;

  // 获取对应的选项数组
  let options = getFieldOptions(field);
  if (field.key === "OriginalPositionId") {
    options = originalPositionOptions.value;
  } else if (field.key === "NewPositionId") {
    options = newPositionOptions.value;
  }

  const index = options.findIndex((option) => option.value === currentValue);
  return index >= 0 ? index : 0;
};

// 获取picker显示的文本
const getPickerDisplayText = (fieldKey: string, field: FieldConfig) => {
  const currentValue = formData.value[fieldKey];
  if (!currentValue) return "";

  // 获取对应的选项数组
  let options = getFieldOptions(field);
  if (field.key === "OriginalPositionId") {
    options = originalPositionOptions.value;
  } else if (field.key === "NewPositionId") {
    options = newPositionOptions.value;
  }

  const option = options.find((option) => option.value === currentValue);
  return option ? option.text : "";
};

// 判断是否为部门字段
const isDepartmentField = (fieldKey: string) => {
  return fieldKey === "OriginalGroupId" || fieldKey === "NewGroupId";
};

// 判断picker是否应该被禁用
const isPickerDisabled = (field: FieldConfig) => {
  // 原岗位字段：需要先选择原部门
  if (field.key === "OriginalPositionId") {
    return !formData.value.OriginalGroupId;
  }
  // 新岗位字段：需要先选择新部门
  if (field.key === "NewPositionId") {
    return !formData.value.NewGroupId;
  }
  return false;
};

// 获取禁用状态的占位符文本
const getDisabledPlaceholder = (field: FieldConfig) => {
  if (field.key === "OriginalPositionId") {
    return "请先选择原部门";
  }
  if (field.key === "NewPositionId") {
    return "请先选择新部门";
  }
  return field.placeholder;
};

// 处理部门选择变化
const handleDepartmentChange = async (value: string) => {
  // 由于我们无法直接知道是哪个字段触发的变化，
  // 我们需要通过比较当前值来判断

  // 检查是否是原部门字段发生了变化
  if (formData.value.OriginalGroupId === value) {
    formData.value.OriginalPositionId = "";
    await loadPositionsByDepartment(value, "original");
  }

  // 检查是否是新部门字段发生了变化
  if (formData.value.NewGroupId === value) {
    formData.value.NewPositionId = "";
    await loadPositionsByDepartment(value, "new");
  }
};

// 根据部门加载岗位列表
const loadPositionsByDepartment = async (
  departmentId: string,
  type: "original" | "new",
) => {
  if (!departmentId) return;

  try {
    console.log(`加载${type}岗位列表，部门ID:`, departmentId);
    const positions = await api.GetSysJobPositions(departmentId);
    console.log(`${type}岗位列表:`, positions);

    const positionOptions = positions.map((position: any) => ({
      value: position.Value || position.Id,
      text: position.Text || position.Name,
    }));

    if (type === "original") {
      originalPositionOptions.value = positionOptions;
      // 更新配置中的选项
      updateFieldOptions("OriginalPositionId", positionOptions);
    } else {
      newPositionOptions.value = positionOptions;
      // 更新配置中的选项
      updateFieldOptions("NewPositionId", positionOptions);
    }
  } catch (error) {
    console.error(`加载${type}岗位列表失败:`, error);
    uni.showToast({
      title: "加载岗位列表失败",
      icon: "none",
    });
  }
};

// 动态选项存储
const dynamicOptions = ref<Record<string, any[]>>({});

// 更新字段选项
const updateFieldOptions = (fieldKey: string, options: any[]) => {
  dynamicOptions.value[fieldKey] = options;
};

// 获取字段选项（优先使用动态选项）
const getFieldOptions = (field: FieldConfig) => {
  return dynamicOptions.value[field.key] || field.options || [];
};

// picker选择处理
const handlePickerChange = (fieldKey: string, field: FieldConfig, e: any) => {
  const index = e.detail.value;

  // 获取对应的选项数组
  let options = getFieldOptions(field);
  if (field.key === "OriginalPositionId") {
    options = originalPositionOptions.value;
  } else if (field.key === "NewPositionId") {
    options = newPositionOptions.value;
  }

  if (options && options[index]) {
    formData.value[fieldKey] = options[index].value;
  }
};

// APP端选择器变化处理
const handleAppSelectorChange = (fieldKey: string, field: FieldConfig, value: any) => {
  formData.value[fieldKey] = value;
};

// 获取文件URL
const getFileUrl = (fileId: string | null) => {
  if (!fileId) return "";
  return `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileId}`;
};

// 文件选择处理
const selectFile = async (fieldKey: string, e: any) => {
  console.log(`选择${fieldKey}文件：`, e);
  const file = e.tempFiles?.[0] || e.tempFiles;
  const filePath = file?.path || file?.tempFilePath;

  if (filePath) {
    try {
      const fileId = await uploadImage(filePath, "file");
      console.log(`${fieldKey}上传成功，文件ID:`, fileId);
      formData.value[fieldKey] = fileId;

      // 更新file-picker显示的数据
      const fileName = file?.name || file?.fileName || "文件";
      fileValues.value[fieldKey] = [
        {
          name: fileName,
          url: getFileUrl(fileId),
          extname: file?.extname || "pdf",
          size: file?.size || 0,
          fileID: fileId,
        },
      ];
    } catch (error) {
      console.error(`${fieldKey}上传失败:`, error);
      uni.showToast({
        title: "文件上传失败，请重试",
        icon: "none",
      });
    }
  }
};

// 文件上传成功回调
const uploadFileSuccess = (fieldKey: string, e: any) => {
  console.log(`${fieldKey}上传成功：`, e);
};

// 文件上传失败回调
const uploadFileFail = (fieldKey: string, e: any) => {
  console.log(`${fieldKey}上传失败：`, e);
  uni.showToast({
    title: "文件上传失败，请重试",
    icon: "none",
  });
};

// 删除文件
const deleteFile = (fieldKey: string, e: any) => {
  console.log(`删除${fieldKey}：`, e);
  formData.value[fieldKey] = "";
  fileValues.value[fieldKey] = [];
};

// 预览文件
const previewFile = async (fieldKey: string) => {
  if (!formData.value[fieldKey]) {
    uni.showToast({
      title: "文件不存在",
      icon: "none",
    });
    return;
  }

  try {
    uni.showLoading({
      title: "加载中...",
    });

    const fileName =
      fileValues.value[fieldKey].length > 0
        ? fileValues.value[fieldKey][0].name
        : "文件";

    await api.previewFile(formData.value[fieldKey], fileName);

    uni.showToast({
      title: "文件加载成功",
      icon: "success",
    });
  } catch (error) {
    console.error("预览文件失败:", error);
    uni.showToast({
      title: "文件预览失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

// 获取多文件ID数组
const getFileIds = (fieldKey: string): string[] => {
  const fileIdsStr = formData.value[fieldKey];
  if (!fileIdsStr) return [];
  return fileIdsStr.split(",").filter((id: string) => id.trim());
};

// 多文件选择处理
const selectMultiFile = async (fieldKey: string, e: any) => {
  console.log(`选择${fieldKey}多文件：`, e);
  const files = e.tempFiles || [];

  if (files.length === 0) return;

  try {
    const uploadPromises = files.map(async (file: any) => {
      const filePath = file?.path || file?.tempFilePath;
      if (filePath) {
        const fileId = await uploadImage(filePath, "file");
        console.log(`${fieldKey}文件上传成功，文件ID:`, fileId);
        return {
          fileId,
          name: file?.name || file?.fileName || "文件",
          extname: file?.extname || "pdf",
          size: file?.size || 0,
        };
      }
      return null;
    });

    const uploadResults = await Promise.all(uploadPromises);
    const validResults = uploadResults.filter((result) => result !== null);

    if (validResults.length > 0) {
      // 获取现有的文件ID
      const existingIds = getFileIds(fieldKey);
      const newIds = validResults.map((result) => result!.fileId);
      const allIds = [...existingIds, ...newIds];

      // 更新表单数据
      formData.value[fieldKey] = allIds.join(",");

      // 更新file-picker显示的数据
      const existingFiles = fileValues.value[fieldKey] || [];
      const newFiles = validResults.map((result) => ({
        name: result!.name,
        url: getFileUrl(result!.fileId),
        extname: result!.extname,
        size: result!.size,
        fileID: result!.fileId,
      }));

      fileValues.value[fieldKey] = [...existingFiles, ...newFiles];
    }
  } catch (error) {
    console.error(`${fieldKey}多文件上传失败:`, error);
    uni.showToast({
      title: "文件上传失败，请重试",
      icon: "none",
    });
  }
};

// 多文件上传成功回调
const uploadMultiFileSuccess = (fieldKey: string, e: any) => {
  console.log(`${fieldKey}多文件上传成功：`, e);
};

// 多文件上传失败回调
const uploadMultiFileFail = (fieldKey: string, e: any) => {
  console.log(`${fieldKey}多文件上传失败：`, e);
  uni.showToast({
    title: "文件上传失败，请重试",
    icon: "none",
  });
};

// 删除多文件
const deleteMultiFile = (fieldKey: string, e: any) => {
  console.log(`删除${fieldKey}多文件：`, e);
  const deleteIndex = e.index;

  // 更新fileValues
  const currentFiles = fileValues.value[fieldKey] || [];
  currentFiles.splice(deleteIndex, 1);
  fileValues.value[fieldKey] = currentFiles;

  // 更新formData中的文件ID字符串
  const fileIds = currentFiles
    .map((file: any) => file.fileID)
    .filter((id: string) => id);
  formData.value[fieldKey] = fileIds.join(",");
};

// 预览多文件
const previewMultiFile = async (fieldKey: string, index: number) => {
  const fileIds = getFileIds(fieldKey);
  if (index >= fileIds.length) {
    uni.showToast({
      title: "文件不存在",
      icon: "none",
    });
    return;
  }

  const fileId = fileIds[index];
  const files = fileValues.value[fieldKey] || [];
  const fileName = files[index]?.name || `文件${index + 1}`;

  try {
    uni.showLoading({
      title: "加载中...",
    });

    await api.previewFile(fileId, fileName);

    uni.showToast({
      title: "文件加载成功",
      icon: "success",
    });
  } catch (error) {
    console.error("预览文件失败:", error);
    uni.showToast({
      title: "文件预览失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

// 重置表单
const resetForm = () => {
  initFormData();
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

// 处理关闭
const handleClose = () => {
  emit("update:show", false);
  resetForm();
};

// 处理确认
const handleConfirm = async () => {
  try {
    // 表单验证
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;

    // 处理部门数据
    const submitData = { ...formData.value };

    console.log("提交前的原始数据:", submitData);
    console.log("部门输入方式:", departmentInputMethod.value);

    // 处理原部门数据
    if (departmentInputMethod.value.original === "manual") {
      // 手动输入模式：保留OriginalDepartmentPosition字段，清理选择模式的字段
      console.log(
        "原部门手动输入模式，OriginalDepartmentPosition:",
        submitData.OriginalDepartmentPosition,
      );
      delete submitData.OriginalGroupId;
      delete submitData.OriginalPositionId;
      delete submitData.OriginalGroupId_manual;
      // OriginalDepartmentPosition字段保留，作为新的传参字段
    } else {
      // 选择输入框模式：保持原来的传参，清理手动输入的字段
      console.log("原部门选择输入框模式");
      delete submitData.OriginalDepartmentPosition;
      delete submitData.OriginalGroupId_manual;
    }

    // 处理新部门数据
    if (departmentInputMethod.value.new === "manual") {
      // 手动输入模式：保留NewDepartmentPosition字段，清理选择模式的字段
      console.log(
        "新部门手动输入模式，NewDepartmentPosition:",
        submitData.NewDepartmentPosition,
      );
      delete submitData.NewGroupId;
      delete submitData.NewPositionId;
      delete submitData.NewGroupId_manual;
      // NewDepartmentPosition字段保留，作为新的传参字段
    } else {
      // 选择输入框模式：保持原来的传参，清理手动输入的字段
      console.log("新部门选择输入框模式");
      delete submitData.NewDepartmentPosition;
      delete submitData.NewGroupId_manual;
    }

    console.log("最终提交的数据:", submitData);

    // 如果有自定义提交函数，使用自定义函数
    if (props.onSubmit) {
      await props.onSubmit(submitData);
    }

    uni.showToast({
      title: "操作成功",
      icon: "success",
    });

    emit("confirm");
    handleClose();
  } catch (error: any) {
    uni.showToast({
      title: error[0].errorMessage,
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 监听显示状态
watch(
  () => props.show,
  (newVal) => {
    if (newVal) {
      popupRef.value?.open();
      resetForm();
    } else {
      popupRef.value?.close();
    }
  },
);

// 监听配置变化，重新初始化表单（保留现有数据）
watch(
  () => props.config,
  () => {
    initFormData(true); // 传入true保留现有数据
  },
  { deep: true },
);

// 监听编辑数据变化，预加载岗位选项
watch(
  () => props.editData,
  async (newEditData) => {
    if (newEditData) {
      // 如果有原部门ID，加载原部门的岗位列表
      if (newEditData.OriginalGroupId) {
        await loadPositionsByDepartment(
          newEditData.OriginalGroupId,
          "original",
        );
      }

      // 如果有新部门ID，加载新部门的岗位列表
      if (newEditData.NewGroupId) {
        await loadPositionsByDepartment(newEditData.NewGroupId, "new");
      }

      // 设置表单数据
      Object.keys(newEditData).forEach((key) => {
        if (formData.value.hasOwnProperty(key)) {
          formData.value[key] = newEditData[key];
        }
      });
    }
  },
  { immediate: true },
);

// 加载部门数据
const loadDepartmentData = async () => {
  try {
    console.log("加载部门数据...");
    const departments = await api.GetParentsTree();
    console.log("部门数据:", departments);

    if (departments && Array.isArray(departments)) {
      departmentData.value = departments;
    }
  } catch (error) {
    console.error("加载部门数据失败:", error);
    uni.showToast({
      title: "加载部门数据失败",
      icon: "none",
    });
  }
};

// 组件挂载
onMounted(async () => {
  initFormData();
  await loadDepartmentData();
});
</script>

<style lang="scss" scoped>
.form-section {
  margin-bottom: 32rpx;
  border-radius: 16rpx;
  background: #ffffff;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);

  .section-header {
    display: flex;
    align-items: center;
    padding: 24rpx 32rpx;
    background: linear-gradient(135deg, #14b8a6 0%, #0891b2 100%);
    position: relative;

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 1rpx;
      background: rgba(255, 255, 255, 0.2);
    }

    .section-icon {
      width: 56rpx;
      height: 56rpx;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
    }

    .section-title {
      flex: 1;

      .title {
        display: block;
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
        line-height: 1.4;
      }

      .subtitle {
        display: block;
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.8);
        margin-top: 4rpx;
        line-height: 1.3;
      }
    }
  }

  .section-content {
    padding: 32rpx;
  }
}

.input-row {
  display: flex;
  gap: 24rpx;
  margin-bottom: 24rpx;

  &:last-child {
    margin-bottom: 0;
  }

  &.single {
    .input-group {
      flex: 1;
    }
  }

  .input-group {
    flex: 1;
    min-width: 0; // 防止flex项目超出容器

    .input-label {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;

      .label-text {
        font-size: 28rpx;
        color: #2c3e50;
        font-weight: 500;
        margin-left: 8rpx;

        .required {
          color: #ef4444;
        }
      }
    }

    .custom-input,
    .custom-picker,
    .custom-textarea {
      border: 1px solid #dcdfe6;
      transition: all 0.3s ease;
      background: #9ca3af;

      &:focus,
      &:focus-within {
        border-color: #14b8a6;
        background: #ffffff;
        box-shadow: 0 0 0 4rpx rgba(20, 184, 166, 0.1);
      }
    }

    .custom-picker {
      .picker-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0px 10px;
        min-height: 35px;
        background: #ffffff;

        // 禁用状态样式
        &.disabled {
          background: #f5f5f5;
          cursor: not-allowed;
        }

        .picker-text {
          font-size: 12px;
          color: #9ca3af; // 默认placeholder颜色为灰色
          flex: 1;

          // 有值时显示黑色
          &.has-value {
            font-size: 14px !important;
            color: #000000 !important;
          }

          // 禁用状态文字样式
          &.disabled {
            color: #ccc !important;
            font-size: 12px !important;
          }

          &:empty::before {
            content: attr(placeholder);
            color: #9ca3af; // placeholder保持灰色
          }
        }
      }
    }

    .custom-textarea {
      min-height: 120rpx;
    }

    .file-upload-container {
      margin-top: 12rpx;

      .file-preview-btn {
        margin-top: 12rpx;
        padding: 12rpx 20rpx;
        background: #f0f9ff;
        border: 2rpx solid #e0f2fe;
        border-radius: 8rpx;
        cursor: pointer;
        transition: all 0.3s ease;

        &:active {
          background: #e0f2fe;
          transform: scale(0.98);
        }

        .preview-content {
          display: flex;
          align-items: center;
          justify-content: center;

          .preview-text {
            font-size: 24rpx;
            color: #374151;
            font-weight: 500;
            margin-left: 6rpx;
          }
        }
      }

      .multi-file-preview {
        display: flex;
        flex-wrap: wrap;
        gap: 8rpx;
        margin-top: 12rpx;

        .file-preview-btn {
          margin-top: 0;
          flex: 0 0 calc(50% - 4rpx);
          min-width: 0;

          .preview-content {
            .preview-text {
              font-size: 22rpx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
      }

      .upload-tips {
        margin-top: 8rpx;
        padding: 8rpx 12rpx;
        background: #f8fafc;
        border-radius: 6rpx;
        border-left: 3rpx solid #14b8a6;

        text {
          font-size: 20rpx;
          color: #6b7280;
          display: block;
          line-height: 1.4;
        }
      }
    }
  }
}

// 强制修改uni-easyinput的.is-input-border样式
:deep(.uni-easyinput) {
  .is-input-border {
    border: none !important;
    border-radius: 0 !important;
  }
}

// 响应式处理，小屏幕时恢复单列
@media (max-width: 750rpx) {
  .form-section {
    margin-bottom: 24rpx;

    .section-header {
      padding: 20rpx 24rpx;

      .section-icon {
        width: 48rpx;
        height: 48rpx;
        margin-right: 16rpx;
      }

      .section-title {
        .title {
          font-size: 28rpx;
        }

        .subtitle {
          font-size: 22rpx;
        }
      }
    }

    .section-content {
      padding: 24rpx;
    }
  }

  .input-row {
    flex-direction: column;
    gap: 0;

    .input-group {
      margin-bottom: 24rpx;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

/* 部门输入方式选择区域样式 */
.department-input-method-section {
  margin-bottom: 24rpx;

  .method-label {
    display: block;
    font-size: 28rpx;
    color: #2c3e50;
    font-weight: 500;
    margin-bottom: 12rpx;
  }
}
</style>
